package com.okyai.cms.generate.tag;

import java.io.IOException;
import java.util.Map;

import com.okyai.cms.generate.utils.ParserUtil;

import cn.hutool.core.io.FileUtil;
import freemarker.cache.StringTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.core.Environment;
import freemarker.core._MiscTemplateException;
import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * @Author: okyai
 * @Description: 自定义引入模板标签
 * @Date: Create in 2020/06/24 15:37
 */
public class IncludeExTag implements TemplateDirectiveModel {

    protected static BeansWrapper build = new BeansWrapperBuilder(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS).build();
    private static final String TEMPLATE_KEY = "template";

    /**
     * 模板根目录
     */
    private String basePath;
    /**
     * 字符串加载器
     */
    private StringTemplateLoader stringLoader;

    public IncludeExTag(String basePath, StringTemplateLoader stringLoader) {
        this.basePath = basePath;
        this.stringLoader = stringLoader;
    }

    @Override
    public void execute(Environment environment, Map params, TemplateModel[] templateModel,
                        TemplateDirectiveBody directiveBody) throws TemplateException, IOException {
        TemplateLoader templateLoader = environment.getConfiguration().getTemplateLoader();
        String path = build.unwrap((TemplateModel) params.get(TEMPLATE_KEY)).toString();
        if (!params.containsKey(TEMPLATE_KEY)) {
            throw new MalformedTemplateNameException("missing required parameter '" + TEMPLATE_KEY, "'");
        }
        if (templateLoader.findTemplateSource(path) == null) {
            throw new _MiscTemplateException(environment, "Missing template file path:" + path);
        }
        //替换模板
        String temp = FileUtil.readString(FileUtil.file(basePath, path).getPath(), "utf-8");
        //正则替换标签
        temp = ParserUtil.regReplace(temp);
        stringLoader.putTemplate("ms:custom:" + path, temp);
        Template template = environment.getTemplateForInclusion("ms:custom:" + path, null, true);
        //引入模板
        environment.include(template);

    }
}
